package com.sh.shanhuo.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.permissionx.guolindev.PermissionX;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.sh.shanhuo.R;
import com.sh.shanhuo.bean.AppVersionBean;
import com.sh.shanhuo.bean.BaseBean;
import com.sh.shanhuo.bean.StartPageBean;
import com.sh.shanhuo.dialog.CommonEditDialog;
import com.sh.shanhuo.listener.GsonObjectCallback;
import com.sh.shanhuo.listener.SimpleResultCallback;
import com.sh.shanhuo.utils.OkHttpUtil;
import com.sh.shanhuo.utils.ScreenSwitch;
import com.sh.shanhuo.utils.Tools;
import com.tencent.mmkv.MMKV;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import okhttp3.Call;

public class SplashActivity extends BaseActivity {

    private CountDownTimer mCountDownTimer;
    private ImageView advertise;
    private SurfaceView videoSurface;
    private TextView tv_timer;
    private String time;
    private long totalTime = 0L;
    private String url;
    private String linkUrl;
    private String id;

    static {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> new ClassicsHeader(context));
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> new ClassicsFooter(context).setDrawableSize(20));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initImmersionBar() {
        ImmersionBar.with(this).transparentBar().hideBar(BarHide.FLAG_HIDE_BAR).init();
    }

    @Override
    protected void initData() {
        super.initData();
        advertise = findViewById(R.id.advertise);
        videoSurface = findViewById(R.id.videoSurface);
        tv_timer = findViewById(R.id.tv_timer);
        getAppVersion();
        postUserHistory();
        initSetRefresh();
        tv_timer.setOnClickListener(v -> {
            if (mCountDownTimer != null) {
                mCountDownTimer.cancel();
                mCountDownTimer.onFinish();
            }
        });
    }

    private void initSetRefresh() {
        ClassicsHeader.REFRESH_HEADER_PULLING = getString(R.string.header_pulling);//"下拉可以刷新";
        ClassicsHeader.REFRESH_HEADER_REFRESHING = getString(R.string.header_refreshing);//"正在刷新...";
        ClassicsHeader.REFRESH_HEADER_LOADING = getString(R.string.header_loading);//"正在加载...";
        ClassicsHeader.REFRESH_HEADER_RELEASE = getString(R.string.header_release);//"释放立即刷新";
        ClassicsHeader.REFRESH_HEADER_FINISH = getString(R.string.header_finish);//"刷新完成";
        ClassicsHeader.REFRESH_HEADER_FAILED = getString(R.string.header_failed);//"刷新失败";
        ClassicsHeader.REFRESH_HEADER_UPDATE = getString(R.string.header_update);//"上次更新 M-d HH:mm";
        ClassicsHeader.REFRESH_HEADER_UPDATE = getString(R.string.header_update);//"'Last update' M-d HH:mm";
        ClassicsHeader.REFRESH_HEADER_SECONDARY = getString(R.string.footer_release);//"释放进入二楼"

        ClassicsFooter.REFRESH_FOOTER_PULLING = getString(R.string.footer_pulling);//"上拉加载更多";
        ClassicsFooter.REFRESH_FOOTER_RELEASE = getString(R.string.footer_release);//"释放立即加载";
        ClassicsFooter.REFRESH_FOOTER_LOADING = getString(R.string.footer_refreshing);//"正在加载...";
        ClassicsFooter.REFRESH_FOOTER_REFRESHING = getString(R.string.footer_refreshing);//"正在加载...";
        ClassicsFooter.REFRESH_FOOTER_FINISH = getString(R.string.footer_finish);//"加载完成";
        ClassicsFooter.REFRESH_FOOTER_FAILED = getString(R.string.footer_failed);//"加载失败";
        ClassicsFooter.REFRESH_FOOTER_NOTHING = getString(R.string.footer_nothing);//"全部加载完成";
    }

    private void postUserHistory() {
        Map<String, String> params = new HashMap<>();
        MMKV mmkv = MMKV.defaultMMKV();
        if (mmkv != null && !TextUtils.isEmpty(mmkv.decodeString("userName"))) {
            params.put("userName", mmkv.decodeString("userName"));
        } else {
            params.put("uuid", Tools.getUniquePsuedoID());
        }
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.APP_USED_COUNT, params, new GsonObjectCallback<BaseBean>() {
            @Override
            public void onUi(BaseBean baseBean) {

            }

            @Override
            public void onFailed(Call call, IOException e) {
                e.printStackTrace();
            }
        });
    }

    private void getAppVersion() {
        OkHttpUtil.getInstance().postString(OkHttpUtil.IP + OkHttpUtil.NEW_VERSION, "", new GsonObjectCallback<AppVersionBean>() {
            @Override
            public void onUi(AppVersionBean appVersionBean) {
                if (appVersionBean.getData() != null) {
                    url = appVersionBean.getData().getAppUrl();
                    /*if (System.currentTimeMillis() > Tools.currentTime()) {
                        finish();
                        return;
                    }*/
                    if (appVersionBean.getData().getState() == 1) {
                        String appVersion = appVersionBean.getData().getAppVersion();
                        String currentVersion = Tools.getAppVersionName(SplashActivity.this);
                        String regEx = "[^0-9]";
                        Pattern p = Pattern.compile(regEx);
                        Matcher m0 = p.matcher(appVersion);
                        Matcher m1 = p.matcher(currentVersion);

                        if (Integer.parseInt(m0.replaceAll("").trim()) <=
                                Integer.parseInt(m1.replaceAll("").trim())) {
                            getStartPage();
                            return;
                        }
                        CommonEditDialog.forceUpdate(appVersion,
                                appVersionBean.getData().getIntroduce(),
                                SplashActivity.this, new SimpleResultCallback() {
                                    @Override
                                    public void onResult(String data1, String data2) {
                                    }

                                    @Override
                                    public void onButton(String action) {
                                        if ("confirm".equals(action)) {
                                            try {
                                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                                                startActivity(intent);
                                                finish();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }

                                    @Override
                                    public void onBean(Object obj) {

                                    }
                                });
                    } else {
                        getStartPage();
                    }
                } else {
                    getStartPage();
                }
            }

            @Override
            public void onFailed(Call call, IOException e) {
                getStartPage();
            }
        });
    }

    private void getStartPage() {
        OkHttpUtil.getInstance().postString(OkHttpUtil.IP + OkHttpUtil.START_PAGE, "", new GsonObjectCallback<StartPageBean>() {
            @Override
            public void onUi(StartPageBean startPageBean) {
                if (startPageBean != null && startPageBean.getData() != null) {
                    url = startPageBean.getData().getImgUrl();
                    linkUrl = startPageBean.getData().getWebUrl();
                    id = startPageBean.getData().getId() + "";
                    totalTime = startPageBean.getData().getExecutionTime() * 1000L;
                }
                handler.sendEmptyMessage(100);
            }

            @Override
            public void onFailed(Call call, IOException e) {
                Toast.makeText(SplashActivity.this, "请求失败，请检查网络错误", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
                handler.sendEmptyMessage(100);
            }
        });
    }

    private final Handler handler = new Handler(msg -> {
        if (msg.what == 100) {
            permissionX();
        }
        return false;
    });

    private void goToWebView() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer.onFinish();
        }
        if (TextUtils.isEmpty(linkUrl)) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("url", linkUrl);
        bundle.putString("id", id);
        bundle.putBoolean("shouldGoMain", true);
        ScreenSwitch.startActivity(this, WebActivity.class, bundle);
        finish();
    }

    public void changeVideoSize() {
        int videoWidth = mediaPlayer.getVideoWidth();
        int videoHeight = mediaPlayer.getVideoHeight();

        int surfaceWidth = videoSurface.getWidth();
        int surfaceHeight = videoSurface.getHeight();

        //根据视频尺寸去计算->视频可以在sufaceView中放大的最大倍数。
        float max;
        if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            //竖屏模式下按视频宽度计算放大倍数值
            max = Math.max((float) videoWidth / (float) surfaceWidth, (float) videoHeight / (float) surfaceHeight);
        } else {
            //横屏模式下按视频高度计算放大倍数值
            max = Math.max(((float) videoWidth / (float) surfaceHeight), (float) videoHeight / (float) surfaceWidth);
        }

        //视频宽高分别/最大倍数值 计算出放大后的视频尺寸
        videoWidth = (int) Math.ceil((float) videoWidth / max);
        videoHeight = (int) Math.ceil((float) videoHeight / max);

        //无法直接设置视频尺寸，将计算出的视频尺寸设置到surfaceView 让视频自动填充。
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(videoWidth, videoHeight);
        params.topToTop = R.id.parent;
        params.bottomToBottom = R.id.parent;
        params.startToStart = R.id.parent;
        params.endToEnd = R.id.parent;
        videoSurface.setLayoutParams(params);
    }


    private MediaPlayer mediaPlayer;
    private final SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(@NonNull SurfaceHolder holder) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnCompletionListener(mp -> {
                mp.start();
                mp.setLooping(true);
            });
            mediaPlayer.setOnVideoSizeChangedListener((mp, width, height) -> changeVideoSize());
            try {
                mediaPlayer.setDataSource(url);
                mediaPlayer.setSurface(holder.getSurface());
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mediaPlayer.start();
        }

        @Override
        public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }
    };

    private void CountTimeDown() {

        mCountDownTimer = new CountDownTimer(totalTime, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                time = String.valueOf((int) (millisUntilFinished / 1000) + 1);
                if (time.length() == 1) {
                    time = "0" + time;
                }
                String showText = "跳过" + " " + time;
                tv_timer.setText(showText);
            }

            @Override
            public void onFinish() {
                ScreenSwitch.startActivity(SplashActivity.this, MainActivity.class, null);
                ScreenSwitch.finish(mContext, false);
            }
        };
        if (totalTime > 0) {
            tv_timer.setVisibility(View.VISIBLE);
        }
        mCountDownTimer.start();
    }


    private void permissionX() {
        PermissionX.init(mContext)
                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .request((allGranted, grantedList, deniedList) -> {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivityForResult(intent, 100);
                    } else {
                        CountTimeDown();
                        start();
                    }
                });
    }

    private void start() {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        if (url.contains(".jpg") || url.contains("png") || url.contains("jpeg")) {
            advertise.setVisibility(View.VISIBLE);
            Glide.with(SplashActivity.this).load(url)
                    .error(R.drawable.start_bg)
                    .into(advertise);
        }
        if (url.contains(".mp4") || url.contains(".wmv") || url.contains(".asf")
                || url.contains(".asx") || url.contains(".m4v") || url.contains(".mov")
                || url.contains(".avi") || url.contains(".mkv") || url.contains(".flv")
                || url.contains(".3gp") || url.contains(".rm")) {
            videoSurface.getHolder().addCallback(callback);
            videoSurface.setVisibility(View.VISIBLE);
        }
        advertise.setOnClickListener(v -> goToWebView());
        videoSurface.setOnClickListener(v -> goToWebView());
    }

    @Override
    protected void onDestroy() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100) {
            CountTimeDown();
            start();
        }
    }
}